<?php
/**
 * 作者:晨光
 * EMAIL:461718846@qq.com
 * DATE:2020/4/8
 */

namespace app\admin\controller;


use app\common\controller\AdminUserBase;
use app\common\model\Admin;
use app\common\model\AdminMenu;
use app\common\model\AdminRole;
use app\common\model\AdminRoleRelated;
use think\Db;
use think\facade\Request;
use think\Validate;

class Auth extends AdminUserBase
{
//    获取侧边栏
    public function get_admin_menu(){
        $data = AdminMenu::getMenu();
        $this->result($data);
    }


    /**
     * 权限节点
     * @return \think\response\View
     */
    public function rule(){
        if (Request::isAjax()){
            $data = AdminMenu::order('sort asc')->append(['open'])->select();
            $this->result($data);
        }
        return view();
    }
    public function rule_save(){
        $param = input();
        $adminMenuModel = new AdminMenu();

        if (empty($param['id'])){
            $res = $adminMenuModel->allowField(true)->isUpdate(false)->save($param);
            saveAdminLog("添加权限节点");
        }else{
            $res = $adminMenuModel->allowField(true)->isUpdate(true)->save($param);
            saveAdminLog("编辑权限节点");
        }

        if ($res !== false){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function rule_del(){
        $id = input('id');
//        判断当前节点下有没有子节点
        $ziNum = Db::name('adminMenu')->where('pid',$id)->count();
        if ($ziNum > 0){
            $this->error('当前节点下有子节点无法删除，请先删除子节点');
        }
        $res = Db::name('adminMenu')->delete($id);
        if ($res !== false){
            saveAdminLog("删除权限节点");
            $this->success();
        }else{
            $this->error();
        }
    }
    /**
     * 权限节点
     * @return \think\response\View
     */

    /**
     * 角色管理
     */
    public function role(){
        if (Request::isAjax()){
            $param = input();
            $where = [];

            if (!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }

            $data = AdminRole::where($where)->order('id desc')->paginate($param['limit']);
            $data = $data->toArray();
            $this->result($data['data'],$data['total']);
        }
        return view();
    }
    public function role_save(){
        $param = input();

        //        验证
        $validate = Validate::make([
            'name|角色名称'  => 'require|unique:adminRole',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }

        $adminRoleModel = new AdminRole();
        if (empty($param['id'])){
            $res = $adminRoleModel->allowField(true)->isUpdate(false)->save($param);
            saveAdminLog("添加角色");
        }else{
            $res = $adminRoleModel->allowField(true)->isUpdate(true)->save($param);
            saveAdminLog("编辑角色");
        }

        if ($res !== false){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function role_edit_save(){
        $param = input();

        $adminRoleModel = new AdminRole();
        $res = $adminRoleModel->allowField(true)->isUpdate(true)->save($param);

        if ($res !== false){
            saveAdminLog("编辑角色");
            $this->success();
        }else{
            $this->error();
        }
    }
    public function role_del(){
        $id = input('id');
        if (empty($id)){
            $id = input('ids');
        }
        $num = Db::name('adminRoleRelated')->where('admin_role_id','in',$id)->count();
        if ($num > 0){
            $this->error('当前角色下有管理员请先接触对应关系');
        }

        $res = Db::name('adminRole')->delete($id);
        if ($res !== false){
            saveAdminLog("删除角色");
            $this->success();
        }else{
            $this->error();
        }
    }
    public function role_rule(){
        $role_id = input('role_id');
        $menuIds = Db::name('adminRole')->where('id',$role_id)->value('admin_menu_id');
        $data = Db::name('adminMenu')->field('pid as pId,id,name')->select();
        foreach ($data as $k=>&$v){

            $v['open'] = true;

            $v['checked'] = false;
            if (in_array($v['id'],explode(',',$menuIds))){
                $v['checked'] = true;
            }

            $dataa[$k] = $v;
        }
        $this->result($data);
    }
    /**
     * 角色管理
     */

    /**
     * 管理员
     */
    public function admin(){
        if (Request::isAjax()){
            $param = input();
            $where = [];

            if (!empty($param['username'])){
                $where[] = ['username','like','%'.$param['username'].'%'];
            }

            if (!empty($param['nick_name'])){
                $where[] = ['nick_name','like','%'.$param['nick_name'].'%'];
            }

            if (!empty($param['state'])){
                $where[] = ['state','=',$param['state']];
            }

            $data = Admin::where($where)->order('id desc')->paginate($param['limit']);

            foreach ($data as $k=>&$v) {
                $admin_role_id = Db::name('adminRoleRelated')->where('admin_id',$v['id'])->column('admin_role_id');
                $v['roles'] = Db::name('adminRole')->where('id','in',$admin_role_id)->select();

                $v['password'] = encry_code($v['password'],'DECODE');

                $data[$k] = $v;
            }

            $data = $data->toArray();
            $this->result($data['data'],$data['total']);
        }
        return view();
    }
    public function admin_save(){
        $param = input();
//        验证
        $validate = Validate::make([
            'username|账号'  => 'require|unique:admin|min:3|chsAlphaNum',
            'nick_name|用户名'  => 'require|unique:admin|min:3|chsAlphaNum',
            'password|密码'  => 'require|min:6',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try {
            $adminModel = new Admin();

            if (!empty($param['password'])){
                $param['password'] = encry_code($param['password']);
            }

            if (empty($param['id'])){
                $adminModel->allowField(true)->isUpdate(false)->save($param);
                $admin_id = $adminModel->getLastInsID();
                saveAdminLog("添加管理");
            }else{
                $adminModel->allowField(true)->isUpdate(true)->save($param);
                $admin_id = $param['id'];
                saveAdminLog("编辑管理员");
            }
//            先删除对应角色再添加
            Db::name('adminRoleRelated')->where('admin_id',$admin_id)->delete();
            if (!empty($param['admin_role_id'])){
                $saveData = [];
                $adminRoleRelateModel = new AdminRoleRelated();
                foreach (explode(',',$param['admin_role_id']) as $v){
                    $saveData[] = [
                        'admin_role_id'=>$v,
                        'admin_id'=>$admin_id
                    ];
                }
                $adminRoleRelateModel->saveAll($saveData);
            }
//            如果修改的是当前登录的用户，那么直接更改session缓存
            if ($admin_id == session('admin.id')){
                session('admin',Db::name('admin')->find($admin_id));
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }
//    普通更改
    public function admin_edit_save(){

        $param = input();
        //        验证
        $validate = Validate::make([
            'username|账号'  => 'require|unique:admin|min:3|chsAlphaNum',
            'nick_name|用户名'  => 'require|unique:admin|min:3|chsAlphaNum',
            'password|密码'  => 'require|min:6',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }

        if (!empty($param['password'])){
            $param['password'] = encry_code($param['password']);
        }


        $adminModel = new Admin();
        $res = $adminModel->allowField(true)->isUpdate(true)->save($param);
//            如果修改的是当前登录的用户，那么直接更改session缓存
        if ($param['id'] == session('admin.id')){
            session('admin',Db::name('admin')->find($param['id']));
        }

        if ($res !== false){
            saveAdminLog("编辑管理员");
            $this->success();
        }else{
            $this->error();
        }

    }
    public function get_admin_role(){
        $data = Db::name('adminRole')->select();
        $this->result($data);
    }
    public function admin_del(){
        $id = input('id');
        if (empty($id)){
            $id = input('ids');
        }
        $res = Db::name('admin')->delete($id);
        if ($res !== false){
            saveAdminLog("删除管理员");
            $this->success();
        }else{
            $this->error();
        }
    }
//    重置密码
    public function reset_password(){
        $id = input('id');
        $adminModel = new Admin();
        $res = $adminModel->allowField(true)->isUpdate(true)->save(['password'=>encry_code('123456')],['id'=>$id]);

        if ($res !== false){
            saveAdminLog("重置密码");
            $this->success();
        }else{
            $this->error();
        }
    }
    /**
     * 管理员
     */
}
